﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using XukaShop.Biz;
using XukaShop.Common;
using XukaShop.Models.ConcertModel;
using XukaShop.Models.Entities;

namespace XukaShop.Areas.Admin.Controllers
{
    public class ProductController : Controller
    {
        private ProductBiz _productBiz = new ProductBiz();
        private BrandBiz _brandBiz = new BrandBiz();
        private LocationBiz _locationBiz = new LocationBiz();

        [HttpGet]
        public ActionResult ProductList()
        {
            List<ProductConcert> lstProduct = new List<ProductConcert>();
            lstProduct = _productBiz.GetAllProduct();
            return View(lstProduct);
        }

        [HttpGet]
        public ActionResult NewProduct()
        {
            List<ProductConcert> lstProduct = new List<ProductConcert>();
            lstProduct = _productBiz.GetListNewProduct();
            return View(lstProduct);
        }

        [HttpGet]
        public ActionResult CommingSoonProduct()
        {
            List<ProductConcert> lstProduct = new List<ProductConcert>();
            lstProduct = _productBiz.GetListCommingSoonProduct();
            return View(lstProduct);
        }

        [HttpGet]
        public ActionResult ProductDetail(string productCode)
        {
            ProductConcert productEnt = new ProductConcert();
            // Flag to know this product have image or not
            var isHaveImage = false;
            var isInputSizeQuantity = false;
            if (!string.IsNullOrEmpty(productCode))
            {
                productEnt = _productBiz.GetProductByCode(productCode);
                if (_productBiz.CountProductImageHas(productCode) > 0)
                {
                    isHaveImage = true;
                }
                // Detech the product is inputed the Size Quantity or not
                isInputSizeQuantity = _productBiz.IsInputedSizeQuantity(productCode);
            }

            // List Product Brand
            ViewBag.BrandList = _brandBiz.GetListBrands();
            // List Gender
            ViewBag.GenderList = CommonFunc.GetListGenderValue();
            // List All Size
            ViewBag.SizeList = CommonFunc.GetListSize();
            // List Available Size
            ViewBag.ProductSize = CommonFunc.GetListProductSize(productCode);
            // List Product Type
            ViewBag.ProductTypeList = CommonFunc.GetListProductType();
            // This product has image or not
            ViewBag.IsHaveImage = isHaveImage;
            // This product is inputed Size Quantity or not
            ViewBag.IsInputedSizeQuantity = isInputSizeQuantity;
            // List Location
            ViewBag.LocationList = _locationBiz.GetListLocation();
            
            return View(productEnt);
        }

        /// <summary>
        /// Save all product information
        /// </summary>
        /// <param name="productModel"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult SaveProduct(ProductConcert productModel)
        {
            bool isUpdate = false;
            var productCode = string.Empty;

            // Update or Insert
            if (!string.IsNullOrEmpty(productModel.Product.ProductCode))
            {
                isUpdate = true;
                productCode = productModel.Product.ProductCode;
            }
            var isSaveSuccess = _productBiz.SaveProduct(productModel.Product, isUpdate);

            // If Save general information successful
            if (isSaveSuccess)
            {
                // If Insert new product, get product code
                if (string.IsNullOrEmpty(productCode))
                {
                    var productSaved = _productBiz.GetProductByName(productModel.Product.ProductName);
                    productCode = productSaved.Product.ProductCode;
                }
                var isSaveSizeSuccess = _productBiz.SaveProductSize(productModel.ListSizeId, productCode);

                // If save size information successful
                if (isSaveSizeSuccess)
                {
                    var isSaveLocationSuccess = _productBiz.SaveProductLocation(productModel.ListLocationId, productCode);
                    if (isSaveLocationSuccess)
                    {
                        return Json(new { Result = CommonConst.SUCCESSFUL, ProductCode = productCode }, JsonRequestBehavior.AllowGet);
                    }
                }
                return Json(new { Result = CommonConst.FAIL, ProductCode = productCode }, JsonRequestBehavior.AllowGet);
            }
            return Json(new { Result = CommonConst.FAIL, ProductCode = productCode }, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public string DeleteProduct(string productCode)
        {
            if (string.IsNullOrEmpty(productCode))
            {
                return CommonConst.FAIL;
            }

            var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\ProductImage", Server.MapPath(@"\")));
            var isSuccessDelete = _productBiz.DeleteProduct(productCode, originalDirectory);
            if (isSuccessDelete)
            {
                return CommonConst.SUCCESSFUL;
            }
            return CommonConst.FAIL;
        }

        /// <summary>
        /// Delete Product Image
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string DeleteProductImage()
        {
            var fileImageName = Request.Params["fileImageName"].Trim();
            var productCode = Request.Params["productCode"].Trim();
            var productImageInfo = Request.Params["productImageInfo"].Trim();
            var folderImage = string.Empty;

            if (string.IsNullOrEmpty(productCode) || string.IsNullOrEmpty(productImageInfo) || string.IsNullOrEmpty(fileImageName))
            {
                return CommonConst.FAIL;
            }

            if (productCode.Contains(CommonConst.MALE_PREFIX))
            {
                folderImage = CommonConst.MALE_PREFIX;
            }
            else
            {
                folderImage = CommonConst.FEMALE_PREFIX;
            }

            if (!string.IsNullOrEmpty(fileImageName))
            {
                Dictionary<string, string> dicProductImageInfo = new Dictionary<string, string>();
                dicProductImageInfo = _productBiz.GetListProductImageInfor(productImageInfo);

                var oldFileName = fileImageName;
                var fileNameToDelete = dicProductImageInfo[oldFileName];
                var isDeleteSuccess = _productBiz.DeleteProductImage(fileNameToDelete, productCode);
                if (isDeleteSuccess)
                {
                    var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\ProductImage", Server.MapPath(@"\")));
                    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), folderImage);

                    // Delete file in folder
                    var path = string.Format("{0}\\{1}", pathString, fileNameToDelete);
                    System.IO.File.Delete(path);

                    // Get information about image of product to load in View
                    string newInfo = _productBiz.RemoveDeletedFileName(productImageInfo, fileNameToDelete);
                    return CommonConst.SUCCESSFUL;
                }
                return CommonConst.FAIL;
            }

            return CommonConst.FAIL;
        }


        /// <summary>
        /// Get List of Product Size by productCode
        /// </summary>
        /// <param name="productCode"></param>
        /// <returns></returns>
        [HttpPost]
        public PartialViewResult GetListProductSize(string productCode)
        {
            List<ProductSize> lstProductSize = new List<ProductSize>();
            lstProductSize = _productBiz.GetListProductSize(productCode);
            return PartialView("_ProductSize", lstProductSize);
        }

        /// <summary>
        /// Update the Quantity for Product Size
        /// </summary>
        /// <param name="productSizeId"></param>
        /// <param name="productSizeQuantity"></param>
        /// <returns></returns>
        [HttpPost]
        public string SaveProductSize(int? productSizeId, int? productSizeQuantity)
        {
            if (productSizeId.HasValue && productSizeQuantity.HasValue)
            {
                ProductSize productSize = new ProductSize();

                // Get Product Size by productSizeId
                productSize = _productBiz.GetProductSizeById(productSizeId.Value);

                // Set the Quantity for Product Size
                productSize.Quantity = productSizeQuantity;

                var isUpdateSuccess = _productBiz.UpdateProductSize(productSize);
                if (isUpdateSuccess)
                {
                    return CommonConst.SUCCESSFUL;
                }
                return CommonConst.FAIL;
            }
            return CommonConst.FAIL;
        }

        /// <summary>
        /// Upload Product Image
        /// </summary>
        /// <returns></returns>
        public ActionResult UploadImageProduct()
        {
            bool isSavedSuccessfully = true;
            string fName = string.Empty;
            var folderImage = string.Empty;
            foreach (string fileName in Request.Files)
            {
                var productCode = Request.Params["productCode"].Trim();
                if (productCode.Contains(CommonConst.MALE_PREFIX))
                {
                    folderImage = CommonConst.MALE_PREFIX;
                }
                else
                {
                    folderImage = CommonConst.FEMALE_PREFIX;
                }
                HttpPostedFileBase file = Request.Files[fileName];

                if (file != null && file.ContentLength > 0)
                {
                    var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\ProductImage", Server.MapPath(@"\")));

                    string pathString = System.IO.Path.Combine(originalDirectory.ToString(), folderImage);

                    bool isExists = System.IO.Directory.Exists(pathString);

                    // If don't exist folder -> create the folder
                    if (!isExists)
                    {
                        System.IO.Directory.CreateDirectory(pathString);
                    }

                    // Path file to get file extendsion
                    var pathFile = pathString + "\\" + file.FileName;

                    // Set file name is the ProductCode
                    fName = _productBiz.GetImageNameToSave(productCode) + Path.GetExtension(pathFile);

                    // Save image information into database
                    ProductImage productImage = new ProductImage();
                    productImage.ProductCode = productCode;
                    productImage.Image = fName;
                    isSavedSuccessfully = _productBiz.SaveProductImage(productImage);

                    // If save into database successfully, save image into folder
                    if (isSavedSuccessfully)
                    {
                        // Save image into folder
                        var path = string.Format("{0}\\{1}", pathString, fName);
                        file.SaveAs(path);
                    }
                }
            }

            if (isSavedSuccessfully)
            {
                return Json(new { Message = fName });
            }
            else
            {
                return Json(new { Message = "Error in saving file" });
            }
        }

        /// <summary>
        /// Get list product's image to show
        /// </summary>
        /// <param name="productCode"></param>
        /// <returns></returns>
        public JsonResult GetListImageProduct(string productCode)
        {
            List<ProductImageConcert> lstProductImage = new List<ProductImageConcert>();
            lstProductImage = _productBiz.GetListProductImageConcertByCode(productCode);
            return Json(lstProductImage, JsonRequestBehavior.AllowGet);
        }
    }
}
